﻿namespace JanusLibAing
{
    using System;
    using System.ComponentModel;
    using System.Drawing.Design;
    using System.Windows.Forms;
    using MultiLang;

    /// <summary>
    /// Custom impl of SelectedPathEditor
    /// Usages:
    /// [Editor(typeof(SelectedDirectoryEditor),typeof(UITypeEditor))]
    /// public string MyDirectory { get; set; }
    /// </summary>
    public class SelectDirectoryEditor : UITypeEditor
    {
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            // uses standard folder browser dialog
            using (FolderBrowserDialog dialog = new FolderBrowserDialog())
            {

                dialog.ShowNewFolderButton = true;

                // setup description
                if (context.PropertyDescriptor != null)
                {
                    if (!string.IsNullOrEmpty(context.PropertyDescriptor.Description))
                    {
                        dialog.Description = context.PropertyDescriptor.Description;
                    }
                    else if (string.IsNullOrEmpty(context.PropertyDescriptor.DisplayName))
                    {
                        dialog.Description = context.PropertyDescriptor.DisplayName;
                    }
                }

                if (string.IsNullOrEmpty(dialog.Description))
                {
                    dialog.Description = ml.ml_string(2, "Выберите каталог");
                }
                // dialog.Description = "Choice directory for autosave";
                dialog.Title = ml.ml_string(3, "Выберите каталог");

                string initialDirectory = value == null ? "" : value.ToString();

                if (string.IsNullOrEmpty(initialDirectory))
                {
                    dialog.RootSpecialFolder = Environment.SpecialFolder.MyDocuments;
                }
                else
                {
                    dialog.InitPath = initialDirectory;
                    dialog.RootSpecialFolder = Environment.SpecialFolder.MyComputer;
                    // dialog.RootPath = initialDirectory;
                }

                // used when inheriting this component
                this.InitializeDialog(dialog, value);

                // show dialog
                if (dialog.ShowDialog(Form.ActiveForm) != DialogResult.OK)
                {

                    // return initial value
                    return value;
                }

                return dialog.SelectedPath;
            }
        }

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        protected virtual void InitializeDialog(FolderBrowserDialog dialog, object value)
        {
        }
    }

}
